<?php
declare (strict_types=1);

namespace app\common\model;

class UserNode extends Base
{
    protected $name = 'user_node';

    protected function user(): object
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,nickname,mobile,node_id,position,is_active,level_id,num_1,num_2,total_1,total_2,surplus_1,surplus_2')
            ->with(['level']);
    }

    protected function fresh(): object
    {
        return $this->hasOne(User::class, 'id', 'new_uid')
            ->field('id,code,nickname,mobile,node_id,position,is_active,level_id,num_1,num_2,total_1,total_2,surplus_1,surplus_2')
            ->with(['level']);
    }

    /**
     * 记录安置关系
     */
    public static function generate($new_uid, $node_id, $position): bool
    {
        try {
            parent::create([
                'uid' => $node_id,
                'algebra' => 1,
                'new_uid' => $new_uid,
                'position' => $position
            ]);
            $time = time();
            parent::where('new_uid', $node_id)
                ->field('uid,algebra + 1 as algebra,"' . $new_uid . '" as new_uid,position,"' . $time . '" as create_time,"' . $time . '" as update_time')
                ->selectInsert([
                    'uid',
                    'algebra',
                    'new_uid',
                    'position',
                    'create_time',
                    'update_time'
                ], (new static())->getName());

            return true;
        } catch (\Exception $e) {

            return false;
        }
    }

    /**
     * 更新团队信息
     */
    public static function renewTeamTotal($uid, $data = [['fx' => '+', 'field' => 'num', 'num' => 1]], $track = 2): bool
    {
        try {
            if ($data) {
                for ($i = 1; $i <= $track; $i++) {
                    $ids = parent::where(['new_uid' => $uid, 'position' => $i])->column('uid');
                    if (!empty($ids)) {
                        $that = User::whereIn('id', $ids);
                        foreach ($data as $item) {
                            $key = $item['field'] . '_' . $i;
                            if ($item['fx'] == '+') {
                                $that->inc($key, floatval($item['num']));
                            } else {
                                $that->dec($key, floatval($item['num']));
                            }
                        }
                        $that->save();
                    }
                }
            }

            return true;
        } catch (\Exception $e) {
            return false;
        }
    }


    public static function getNodeId($platoonId)
    {
        $uid = User::where('platoon_id', $platoonId)->where('is_sub', 1)->order('id', 'desc')->value('id') ?? 0;
        return $uid;
    }

}